/* 
 * File:   delivery_mimer.h
 * Author: james
 *
 * Created on 2011年4月3日, 上午10:13
 */

#ifndef DELIVERY_MIMER_H
#define	DELIVERY_MIMER_H

#include <string>
#include <map>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>

#include "memcache_connection.h"

#include "prepare.h"

namespace edm{
    namespace prepare{
        //! cook task template to the real message mime body
        class delivery_mimer_t
        {
        public:
            delivery_mimer_t(const std::string& mc_host, const std::string& mc_port);
            ~delivery_mimer_t();
            //! start mimer service
            int start(const char* bind_ip,
                      callback_cooked_t cooked_callback , 
                      callback_template_missed_t template_missed_callback,
                      callback_error_t callback_error);
            //! stop mimer service
            int stop();
            //! cook delivery request
            void cook_delivery(delivery_t* delivery);
            //! mc key
            std::string memcache_key(edm_task_id_t taskid, const char* suffix);
        private:
            int  cooking_message_i(delivery_t* delivery, std::string& temp);
            //! 
            void cook_delivery_i(delivery_t* delivery);
            //! 
            void timer_template_clear_i(edm_task_id_t taskid);
        private:
            //! memcahe connection
            edm::network::memcache_connection_t  m_memcache_connection;
            //! identify whether service is running
            bool m_started;
            //! m_bind_ip
            std::string m_bind_ip;
            //! cooked callback
            callback_cooked_t m_callback_cooked;
            //! template missed callback
            callback_template_missed_t m_callback_template_missed;
            //! error occur callback
            callback_error_t m_callback_error;
            //! io service object of boost for deadline time and thread working
            boost::asio::io_service m_io_service;
            //! io service work object of boost for keeping io service is running
            boost::scoped_ptr<boost::asio::io_service::work> m_io_work;
            //! thread pool
            boost::scoped_ptr<boost::thread>    m_thread;
            //! delivery waiting list
            delivery_list_t m_waiting_deliverys;
            //! template
            std::map<edm_task_id_t, std::string> m_subjects;
            std::map<edm_task_id_t, std::string> m_templates;
        };
    }
}

#endif	/* DELIVERY_MIMER_H */

